import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sports_new/entity/king/king_rank_entity.dart';
import 'package:sports_new/utils/utils.dart';
import '../../server/api/king_api.dart';

class KingRankLogic extends GetxController with GetTickerProviderStateMixin{
  int? type = Get.arguments;
  List<String> rankTypeList = ["week","month","day"];
  List<String> rankNameList = ["周榜","月榜","日榜"];
  List<String> updateTimeList = ["次周一14时","次月1日14时","赛后30分钟"];
  late final TabController tabController;
  EasyRefreshController refreshController = EasyRefreshController(controlFinishLoad: true);
  int _tabIndex = Get.parameters['index']?.toInt() ?? 0;
  List<String>? dayList;
  List<String>? days;
  List<List<KingRankItem>?> rankList = [];

  int get tabIndex => _tabIndex;
  String get rankName => rankNameList[(type ?? 1)-1];
  String get rankType => rankTypeList[(type ?? 1)-1];
  String get updateTime => updateTimeList[(type ?? 1)-1];

  set tabIndex(int value) {
    _tabIndex = value;
    update();
  }

  @override
  void onReady() async{
    await getData();
    tabController.addListener(() {
      tabIndex = tabController.index;
      getData(index: tabController.index);
      refreshController.resetFooter();
    });
    super.onReady();
  }

  Future getData({int? index}) async{
    var data = await KingApi.getKingRank(index == null?"":days![index],
      type ?? 0, 1, type==1?99:99);
    if(index == null){
      days = data.dayList?.map((e) => e.day1 ?? "").toList() ?? [];
      dayList = data.dayList?.map((e) => e.day ?? "").toList() ?? [];
      rankList = List.generate(dayList?.length ?? 0, (index) => null);
      if(tabIndex != 0){
        var d = await KingApi.getKingRank(days![tabIndex],
          type ?? 0, 1, type==1?99:99);
        rankList[tabIndex] = d.rankList ?? [];
      }else{
        int? i = data.dayList?.indexWhere((element) => element.selected == true);
        tabIndex =  i==null || i==-1?0:i;
        var d = await KingApi.getKingRank(days![tabIndex],
            type ?? 0, 1, type==1?99:99);
        rankList[tabIndex] = d.rankList ?? [];
      }
      tabController =TabController(length: dayList?.length ?? 0, vsync: this,initialIndex: tabIndex);
    }else{
      rankList[index] = data.rankList ?? [];
    }
    update();
  }

  Future updateData() async{
    refreshController.finishLoad(IndicatorResult.noMore);
    // if(type == 1) return;
    // pageIndex[tabIndex] += 1;
    // var data = await KingApi.getKingRank(days![tabIndex],
    //   type ?? 0, pageIndex[tabIndex], 15);
    // rankList[tabIndex]?.addAll(data.rankList ?? []);
    // refreshController.finishLoad(
    //   rankList[tabIndex]?.length != pageIndex[tabIndex]*15?
    //   IndicatorResult.noMore:IndicatorResult.success);
    // update();
  }
}